<?php

/**
 * CRUD controller. Contains base CRUD logic (Create/Read/Update/Delete)
 *
 * @throws Ext_Exception
 * @category Ext
 * @package Controllers
 */
abstract class Ext_Controller_Action_Crud extends Zend_Controller_Action
{
    /**
     * Class name of DbTable
     *
     * @var string
     */
    protected $_tableName;

    /**
     * Class name of add/update form 
     *
     * @var string
     */
    protected $_formName;

    /**
     * @var int
     */
    protected $_itemCountPerPage = 20;

    /**
     * Messages
     *
     * @var array
     */
    protected $_messages = array(
        'entityAdded'   => 'Entity has been added',
        'entityUpdated' => 'Entity has been updated',
        'entityDeleted' => 'Entity has been deleted'
    );

    public function indexAction()
    {
        $this->view->entities = new Zend_Paginator(
            Ext_App::getTable($this->_tableName)->fetchPaginatorAdapter()
        );
        $this->view->entities->setCurrentPageNumber($this->_getParam('page', 1));
        $this->view->entities->setItemCountPerPage($this->_itemCountPerPage);
        $this->view->entities->setPageRange(Ext_App::getSetting('limits.page_range'));
    }

    public function addAction()
    {
        $this->_form();
    }

    public function editAction()
    {
        $entity = $this->_findEntity();

        if (!$entity) {
            $this->_helper->error->notFound();
        }

        $this->_form($entity);
    }

    public function deleteAction()
    {
        $entity = Doctrine::getTable($this->_getEntityName())->find($this->_getParam('id'));

        if (!$entity) {
            $this->_helper->error->notFound();
        }

        $entity->delete();

        $this->_helper->messenger->success($this->_messages['entityDeleted']);

        $this->_redirectToIndex();
    }

    protected function _form(Doctrine_Record $entity)
    {
        $form = $this->_getForm();
        $form->setDefaults($entity->toArray());

//        if ($this->getRequest()->getParam('cancel')) {
//            $this->_redirectToIndex();
//        }

        if ($this->getRequest()->isPost()
                && $form->isValid($this->getRequest()->getParams()))
        {
            $messageKey = $entity->exists() ? 'entityUpdated' : 'entityAdded';

            $this->_helper->messenger->success($this->_messages[$messageKey]);
        
            $this->_saveEntity($entity, $form);

            $this->_redirectToIndex();
        }

        $this->view->form = $form;
    }

    /**
     * Returns form instance
     *
     * @return Zend_Form
     */
    protected function _getForm()
    {
        $formName = $this->_getFormName();
        return new $formName();
    }

    /**
     * Returns entity instance
     *
     * @return Doctrine_Record
     */
    protected function _getEntity()
    {
        $entityName = $this->_getEntityName();
        return new $entityName();
    }

    /**
     * Method to save entity. May be refined in child controller
     * @return void
     */
    protected function _saveEntity($entity)
    {
        $entity->save();
    }

    protected function _findEntity()
    {
        
    }

    protected function _redirectToIndex()
    {
        $this->_helper->redirector->gotoSimple(
            'index',
            $this->getRequest()->getControllerName(),
            $this->getRequest()->getModuleName()
        );
    }
}